package com.company.bookstore.security;

import com.company.bookstore.entities.user_admin_module.Admin;
import com.company.bookstore.entities.user_admin_module.Roles;
import com.company.bookstore.service.user_admin_module.AdminService;
import com.company.bookstore.service.user_admin_module.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * AdminnamePasswordProvider
 * 管理员名字密码验证类
 * @blame Android Team
 */
@Component
@Slf4j
public class AdminnamePasswordProvider implements AuthenticationProvider {

    @Resource
    AdminService adminService;

    @Resource
    RoleService roleService;
    @Resource
    BCryptPasswordEncoder passwordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        Admin admin = (Admin) adminService.loadUserByUsername(username);
        if (null == admin){
            log.info("没有该账号");
            throw new UsernameNotFoundException("没有该账号");
        }
        if (!passwordEncoder.matches(password,admin.getPassword())){
            log.info("没有该账号");
            throw new BadCredentialsException("密码错误");
        }
        if (admin.getDeleted() == 1){
            log.info("该账号已被回收");
            throw new BadCredentialsException("该账号已被回收");
        }
        if (!admin.isEnabled()){
            log.info("该账号已经被冻结");
            throw new BadCredentialsException("账号已经被禁用");
        }
        Roles role  = roleService.getById(admin.getFkRoleId());
        admin.setPower(AuthorityUtils.createAuthorityList(role.getRoleName()));
        return new UsernamePasswordAuthenticationToken(admin, password, admin.getAuthorities());
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(AdminnamePasswordToken.class);
    }
}
